package pages

import (
	"strings"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"github.com/yourusername/tinput/internal/core/storage"
)

// NewHistoryPage 创建历史查询页面
func NewHistoryPage(window fyne.Window) fyne.CanvasObject {
	// 创建历史记录列表
	var historyList *widget.List
	historyList = widget.NewList(
		func() int {
			return len(storage.GetHistory())
		},
		func() fyne.CanvasObject {
			// 创建水平容器，包含标签和删除按钮
			label := widget.NewLabel("History item")

			label.Resize(fyne.NewSize(300, 30))
			label.Truncation = fyne.TextTruncateClip
			label.Wrapping = fyne.TextWrapOff
			deleteBtn := widget.NewButton("Delete", func() {})
			return container.NewBorder(nil, nil, label, deleteBtn)
		},
		func(i widget.ListItemID, object fyne.CanvasObject) {
			history := storage.GetHistory()
			if i < len(history) {
				item := history[i]
				hbox := object.(*fyne.Container)
				label := hbox.Objects[0].(*widget.Label)
				label.SetText(strings.ReplaceAll(item.Input+" → "+item.Corrected, "\n", ""))

				// 设置删除按钮的点击事件
				deleteBtn := hbox.Objects[1].(*widget.Button)
				deleteBtn.OnTapped = func() {
					// 删除对应的历史记录
					storage.DeleteHistory(i)
					// 刷新列表
					listRef := historyList
					listRef.Refresh()
				}
			}
		},
	)

	// 创建刷新按钮
	refreshButton := widget.NewButton("refresh", func() {
		historyList.Refresh()
	})

	// 创建布局
	content := container.NewBorder(
		refreshButton,
		nil,
		nil,
		nil,
		historyList,
	)

	return content
}
